package zzhyc.keystore

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdDislike
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd
import com.bytedance.sdk.openadsdk.TTNativeExpressAd
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot
import zzhyc.keystore.databinding.ActivityTwoBinding

private const val TAG = "TwoActivity"

class TwoActivity : AppCompatActivity() {

    private val binding by lazy { ActivityTwoBinding.inflate(layoutInflater) }
    private var mTTRewardVideoAd: TTRewardVideoAd? = null
    private var bannerAd: TTNativeExpressAd? = null
    private var fullScreenVideoAd: TTFullScreenVideoAd? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        Log.i(TAG, "TwoActivity/onCreate")
        innitBanner()

        //激励按钮
        binding.twoBtnJiLi.setOnClickListener {
            buildRewardAdslot()
            loadRewardAd()
        }

        //插屏
        binding.twoBtnCha.setOnClickListener {
            initChaPingVideo()
        }

        //跳转draw信息流页面
        binding.twoBtnDraw.setOnClickListener {
            startActivity(Intent(this, DrawActivity::class.java))
        }
    }

    //--------------------- banner_Start ----------------------------------
    private fun innitBanner() {
        binding.twoBanner.removeAllViews()

        val bannerSlot = AdSlot.Builder()
            .setCodeId(ConstantsKey.BANNER_APP_ID)  //广告位ID
            .setImageAcceptedSize(
                UIUtils.getScreenWidthInPx(this), UIUtils.dp2px(this, 150f)
            ).build()
        val adNativeLoader: TTAdNative = TTAdSdk.getAdManager().createAdNative(this)
        adNativeLoader.loadBannerExpressAd(
            bannerSlot, object : TTAdNative.NativeExpressAdListener {
                override fun onNativeExpressAdLoad(ads: MutableList<TTNativeExpressAd>?) {  //广告加载成功
                    Log.i(TAG, "banner/onNativeExpressAdLoad")
                    ads?.let {
                        if (it.size > 0) {
                            val ad: TTNativeExpressAd = it[0]
                            bannerAd = ad
                            showBannerView(bannerAd) //注 ：bannerContainer为展示Banner广告的容器
                        }
                    }
                }

                override fun onError(code: Int, message: String?) { //广告加载失败
                    Log.i(TAG, "banner/onError--- ${code}，msg-- ${message}")
                }
            })
    }

    //展示Banner广告
    private fun showBannerView(bannerAd: TTNativeExpressAd?) {
        bannerAd?.setExpressInteractionListener(object :
            TTNativeExpressAd.ExpressAdInteractionListener {
            override fun onAdClicked(view: View?, type: Int) {
                //广告点击
            }

            override fun onAdShow(view: View?, type: Int) { //广告展示
                //获取展示广告相关信息，需要再show回调之后进行获取
                val manager = bannerAd.mediationManager
                if (manager != null && manager.showEcpm != null) {
                    val ecpm = manager.showEcpm.ecpm //展示广告的价格
                    val sdkName = manager.showEcpm.sdkName  //展示广告的adn名称
                    val slotId = manager.showEcpm.slotId //展示广告的代码位ID
                    Log.i(TAG, "banner/onAdShow-- 展示广告的价格- ${ecpm}")
                }
            }

            override fun onRenderFail(view: View?, msg: String?, code: Int) {   //广告渲染失败
                Log.i(TAG, "banner/onRenderFail-- ${code}，msg-- ${msg}")
            }

            override fun onRenderSuccess(view: View?, width: Float, height: Float) {    //广告渲染成功
                Log.i(TAG, "banner/onRenderSuccess-- 广告渲染成功")
            }
        })
        //设置dislike回调
        bannerAd?.setDislikeCallback(this, object : TTAdDislike.DislikeInteractionCallback {
            override fun onShow() {
            }

            override fun onSelected(position: Int, value: String?, enforce: Boolean) {
                //用户点击了dislike按钮
                binding.twoBanner.removeAllViews()
            }

            override fun onCancel() {
            }
        })
        val bannerView: View? = bannerAd?.expressAdView //获取Banner View
        if (bannerView != null) {
            binding.twoBanner.removeAllViews()
            binding.twoBanner.addView(bannerView)
        }
    }
    //--------------------- banner_End ----------------------------------

    //-------------------- 激励视频Start --------------------------------
    //构造激励视频广告的Adlsot
    private fun buildRewardAdslot(): AdSlot {
        return AdSlot.Builder()
            .setCodeId(ConstantsKey.JILI_APP_ID)  //广告位ID
            .setOrientation(TTAdConstant.VERTICAL)  //激励视频方向
            .setMediationAdSlot(
                MediationAdSlot.Builder()
                    .setMuted(false)
                    .setRewardName("奖励金银奖")
                    .setRewardAmount(990)
                    .setExtraObject("gold", "880")
                    .build()
            ).build()
    }

    //加载激励视频
    private fun loadRewardAd() {
        val adNativeLoader = TTAdSdk.getAdManager().createAdNative(this)
        //这里为激励视频的简单功能，如需使用复杂功能，如gromore的服务端奖励验证，请参考demo中的AdUtils.kt类中激励部分
        adNativeLoader.loadRewardVideoAd(
            buildRewardAdslot(),
            object : TTAdNative.RewardVideoAdListener {
                override fun onError(errorCode: Int, errorMsg: String?) {
                    Log.i(TAG, "onError/广告加载失败-- code-- ${errorCode}，msg-- ${errorMsg}")
                    //广告加载失败
                }

                override fun onRewardVideoAdLoad(ttRewardVideoAd: TTRewardVideoAd?) {
                    mTTRewardVideoAd = ttRewardVideoAd
                    //广告加载成功
                    Log.i(TAG, "onRewardVideoAdLoad--广告加载成功")
                }

                override fun onRewardVideoCached() {
                    //广告缓存成功 此api已经废弃，请使用onRewardVideoCached(ttRewardVideoAd: TTRewardVideoAd?)
                }

                override fun onRewardVideoCached(ttRewardVideoAd: TTRewardVideoAd?) {
                    Log.i(TAG, "onRewardVideoCached")
                    mTTRewardVideoAd = ttRewardVideoAd
                    //广告缓存成功 在此回调中进行广告展示
                    showRewardAD(ttRewardVideoAd)
                }
            })
    }

    //展示激励视频
    private fun showRewardAD(ttRewardVideoAd: TTRewardVideoAd?) {
        ttRewardVideoAd?.let {
            val mIsReady = it.mediationManager.isReady
            Log.i(TAG, "isReady-- ${mIsReady}")
            if (mIsReady) {
                it.setRewardAdInteractionListener(object :
                    TTRewardVideoAd.RewardAdInteractionListener {
                    override fun onAdShow() {
                        Log.i(TAG, "激励视频/onAdShow")
                        //广告展示
                        //获取展示广告相关信息，需要再show回调之后进行获取
                        val manager = it.mediationManager;
                        if (manager != null && manager.showEcpm != null) {
                            val ecpm = manager.showEcpm.ecpm //展示广告的价格
                            val sdkName = manager.showEcpm.sdkName  //展示广告的adn名称
                            val slotId = manager.showEcpm.slotId //展示广告的代码位ID
                            Log.i(TAG, "激励视频/展示价格-- ${ecpm}")
                        }
                    }

                    override fun onAdVideoBarClick() {
                        Log.i(TAG, "激励视频/onAdVideoBarClick/广告点击")
                        //广告点击
                    }

                    override fun onAdClose() {
                        //广告关闭
                        Log.i(TAG, "激励视频/onAdClose/广告关闭")
                    }

                    override fun onVideoComplete() {
                        //广告视频播放完成
                        Log.i(TAG, "激励视频/onVideoComplete/广告视频播放完成")
                    }

                    override fun onVideoError() {
                        //广告视频错误
                        Log.i(TAG, "激励视频/onVideoError/广告视频错误")
                    }

                    override fun onRewardVerify(
                        rewardVerify: Boolean, rewardAmount: Int, rewardName: String?,
                        errorCode: Int, errorMsg: String?
                    ) {
                        //奖励发放 已废弃 请使用 onRewardArrived 替代
                    }

                    override fun onRewardArrived(
                        isRewardValid: Boolean, rewardType: Int, extraInfo: Bundle?
                    ) {
                        //奖励发放 （ rewardType-- 0:基础奖励 >0:进阶奖励）
                        Log.i(
                            TAG,
                            "激励视频/onRewardArrived/奖励是否有效-- ${isRewardValid}，奖励类型-- ${rewardType}"
                        )
                        extraInfo?.let { info ->
                            //奖励名称
                            val rewardName =
                                info.getString(TTRewardVideoAd.REWARD_EXTRA_KEY_REWARD_NAME)
                            //奖励数量
                            val rewardNum =
                                info.getInt(TTRewardVideoAd.REWARD_EXTRA_KEY_REWARD_AMOUNT)
                            //建议奖励百分比
                            val rewardProPose =
                                info.getFloat(TTRewardVideoAd.REWARD_EXTRA_KEY_REWARD_PROPOSE)
                            Log.i(
                                TAG,
                                "激励视频/奖励名称-- ${rewardName}，奖励数量-- ${rewardNum}，建议奖励百分比-- ${if (rewardType > 0) "进阶奖励" else "基础奖励"}"
                            )
                        }
                    }

                    override fun onSkippedVideo() {
                        //广告跳过
                        Log.i(TAG, "激励视频/onSkippedVideo/广告跳过")
                    }
                })
                it.showRewardVideoAd(this) //展示插全屏广告
            }
        }
    }

    //-------------------- 激励视频End --------------------------------

    //-------------------- 插屏视频Start -----------------------------------
    private fun initChaPingVideo() {
        val chaPingSlot = AdSlot.Builder()
            .setCodeId(ConstantsKey.CHA_APP_ID).setOrientation(TTAdConstant.VERTICAL)
            .setMediationAdSlot(MediationAdSlot.Builder().setMuted(true).build()).build()

        val adNativeLoader = TTAdSdk.getAdManager().createAdNative(this)
        adNativeLoader.loadFullScreenVideoAd(
            chaPingSlot, object : TTAdNative.FullScreenVideoAdListener {
                override fun onError(code: Int, message: String?) {
                    //广告加载失败
                    Log.i(TAG, "插全屏/onError-- ${code}， msg-- ${message}")
                }

                override fun onFullScreenVideoAdLoad(ad: TTFullScreenVideoAd?) {
                    //广告加载成功
                    Log.i(TAG, "插全屏/onFullScreenVideoAdLoad")
                    fullScreenVideoAd = ad
                }

                override fun onFullScreenVideoCached() {
                    //广告缓存成功，此回调已经废弃，请使用onFullScreenVideoCached(ad: TTFullScreenVideoAd?)
                }

                override fun onFullScreenVideoCached(ad: TTFullScreenVideoAd?) {
                    Log.i(TAG, "插全屏/onFullScreenVideoCached")
                    fullScreenVideoAd = ad
                    //广告缓存成功，在此回调中展示广告
                    showInterstitialFullAd(fullScreenVideoAd)
                }
            })
    }

    //展示插全屏广告
    fun showInterstitialFullAd(ad: TTFullScreenVideoAd?) {
        ad?.let {
            if (it.mediationManager.isReady) {
                it.setFullScreenVideoAdInteractionListener(object :
                    TTFullScreenVideoAd.FullScreenVideoAdInteractionListener {
                    override fun onAdShow() {
                        Log.i(TAG, "插全屏/onAdShow")
                        //广告展示
                        val manager = it.mediationManager
                        //获取展示广告相关信息，需要再show回调之后进行获取
                        if (manager != null && manager.showEcpm != null) {
                            val ecpm = manager.showEcpm.ecpm //展示广告的价格
                            val sdkName = manager.showEcpm.sdkName  //展示广告的adn名称
                            val slotId = manager.showEcpm.slotId //展示广告的代码位ID
                            Log.i(TAG, "插全屏/onAdShow-- 展示价格- ${ecpm}")
                        }
                    }

                    override fun onAdVideoBarClick() {
                        //广告点击
                        Log.i(TAG, "插全屏/onAdVideoBarClick")
                    }

                    override fun onAdClose() {
                        //广告关闭
                        Log.i(TAG, "插全屏/onAdClose")
                    }

                    override fun onVideoComplete() {
                        //广告播放完成
                        Log.i(TAG, "插全屏/onVideoComplete")
                    }

                    override fun onSkippedVideo() {
                        //广告跳过
                        Log.i(TAG, "插全屏/onSkippedVideo")
                    }
                })
                it.showFullScreenVideoAd(this) //展示插全屏广告
            }
        }
    }

    //-------------------- 插屏视频End -----------------------------------
    //-------------------- ||||||||||||||||||||||| -----------------------------------

    private var mExitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mExitTime > 2000) {
                Toast.makeText(this, getString(R.string.exit_program), Toast.LENGTH_SHORT).show()
                mExitTime = System.currentTimeMillis()
            } else {
                if (!this.isFinishing) {
                    finishAndRemoveTask()
                }
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mTTRewardVideoAd != null && mTTRewardVideoAd!!.mediationManager != null) {
            mTTRewardVideoAd!!.mediationManager.destroy()
        }
        bannerAd?.destroy()
        fullScreenVideoAd?.mediationManager?.destroy()
    }
}